import torch

from torch_geometric.utils import get_mesh_laplacian


def test_get_mesh_laplacian_of_cube():
    pos = torch.tensor([
        [1.0, 1.0, 1.0],
        [1.0, -1.0, 1.0],
        [-1.0, -1.0, 1.0],
        [-1.0, 1.0, 1.0],
        [1.0, 1.0, -1.0],
        [1.0, -1.0, -1.0],
        [-1.0, -1.0, -1.0],
        [-1.0, 1.0, -1.0],
    ])

    face = torch.tensor([
        [0, 1, 2],
        [0, 3, 2],
        [4, 5, 1],
        [4, 0, 1],
        [7, 6, 5],
        [7, 4, 5],
        [3, 2, 6],
        [3, 7, 6],
        [4, 0, 3],
        [4, 7, 3],
        [1, 5, 6],
        [1, 2, 6],
    ])

    edge_index, edge_weight = get_mesh_laplacian(pos, face.t(),
                                                 normalization='rw')

    assert edge_index.tolist() == [
        [
            0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4,
            4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 0, 1, 2, 3, 4, 5, 6, 7
        ],
        [
            1, 2, 3, 4, 0, 2, 4, 5, 6, 0, 1, 3, 6, 0, 2, 4, 6, 7, 0, 1, 3, 5,
            7, 1, 4, 6, 7, 1, 2, 3, 5, 7, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 7
        ],
    ]

    assert torch.allclose(
        edge_weight,
        torch.tensor([
            0.375, 0.0, 0.375, 0.375, 0.3, 0.3, 0.0, 0.3, 0.0, 0.0, 0.375,
            0.375, 0.375, 0.3, 0.3, 0.0, 0.0, 0.3, 0.3, 0.0, 0.0, 0.3, 0.3,
            0.375, 0.375, 0.375, 0.0, 0.0, 0.3, 0.0, 0.3, 0.3, 0.375, 0.375,
            0.0, 0.375, -1.125, -0.9, -1.125, -0.9, -0.9, -1.125, -0.9, -1.125
        ]))


def test_get_mesh_laplacian_of_irregular_triangular_prism():
    pos = torch.tensor([
        [0.0, 0.0, 0.0],
        [4.0, 0.0, 0.0],
        [0.0, 0.0, -3.0],
        [1.0, 5.0, -1.0],
        [3.0, 5.0, -1.0],
        [2.0, 5.0, -2.0],
    ])

    face = torch.tensor([
        [0, 1, 2],
        [3, 4, 5],
        [0, 1, 4],
        [0, 3, 4],
        [1, 2, 5],
        [1, 4, 5],
        [2, 0, 3],
        [2, 5, 3],
    ])

    edge_index, edge_weight = get_mesh_laplacian(pos, face.t(),
                                                 normalization='rw')

    assert edge_index.tolist() == [
        [
            0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5,
            5, 5, 0, 1, 2, 3, 4, 5
        ],
        [
            1, 2, 3, 4, 0, 2, 4, 5, 0, 1, 3, 5, 0, 2, 4, 5, 0, 1, 3, 5, 1, 2,
            3, 4, 0, 1, 2, 3, 4, 5
        ],
    ]

    assert torch.allclose(
        edge_weight,
        torch.tensor([
            0.09730332, 0.15039921, 0.05081503, 0.00000000, 0.08726977,
            0.03521059, 0.05363689, 0.00723919, 0.14497279, 0.03784235,
            0.01629947, 0.03438699, 0.08362866, 0.02782887, 0.24252312,
            0.40727590, 0.00000000, 0.08728313, 0.21507657, 0.38582093,
            0.01117009, 0.04936920, 0.34247482, 0.36583540, -0.29851755,
            -0.18335645, -0.23350160, -0.76125660, -0.68818060, -0.76884955
        ]))
